#include "stm32f10x.h" // Device header
#include "OLED.h"
uint16_t new_paulse = 0;
uint16_t old_cnt = 0;  
uint16_t new_cnt = 0;  
int differ_cnt = 0;  
int sum_cnt = 0;
float current_angle ;

void IC_Init(void)
{
    
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); // PA6/PA7时钟
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);  // TIM4时钟

    GPIO_InitTypeDef GPIO_InitStructure;	
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

 
    TIM_TimeBaseInitTypeDef  TIM_TimeBaseInitStructure;
    TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitStructure.TIM_Period = 65536-1;
    TIM_TimeBaseInitStructure.TIM_Prescaler = 0;
    TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM4, &TIM_TimeBaseInitStructure);

    
    TIM_EncoderInterfaceConfig(TIM4, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);

    
    TIM_ICInitTypeDef TIM_ICInitStructure;
    TIM_ICStructInit(&TIM_ICInitStructure);
    TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
    TIM_ICInitStructure.TIM_ICFilter = 0x0F;
    TIM_ICInit(TIM4, &TIM_ICInitStructure);
    
    TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
    TIM_ICInitStructure.TIM_ICFilter = 0x0F;
    TIM_ICInit(TIM4, &TIM_ICInitStructure);
    
    // 7. 计数器初始化与使能（TIM4，参数不变）
    TIM_SetCounter(TIM4, 0);
    old_cnt = 0;  // 初始化旧计数，避免随机值
    sum_cnt = 0;  // 初始化总脉冲数，避免随机值
    TIM_Cmd(TIM4, ENABLE);
}

// IC_Update函数：仅修改TIM_GetCounter的实例为TIM4
void IC_Update(void)
{    
  uint16_t new_cnt1 = TIM_GetCounter(TIM4) ; 
  uint16_t new_cnt2 = TIM_GetCounter(TIM4) ; 
  new_cnt = TIM_GetCounter(TIM4); 
  
    differ_cnt = new_cnt - old_cnt;
    if(differ_cnt > (65536/2))       
    {
      differ_cnt -= 65536;
    }                               
    else if(differ_cnt < (-65536/2))
    {
      differ_cnt += 65536;
    }
    else {}
    sum_cnt += differ_cnt;
    old_cnt = new_cnt ;      
    current_angle = (float)(sum_cnt % 22) / 22 * 360.0f;
    if(current_angle < 0)
      current_angle += 360.0f;
    OLED_ShowNum (2,1,sum_cnt,4);
  
}

